/*
 * Packet.cpp
 *
 *  Created on: 19 Jun 2013
 *      Author: Shameegh
 */

#include "Packet.h"

//Constructors/Destructors
Packet::Packet() {
	Init();
}

Packet::Packet(QString url)
{
	URL = url;
	Init();
}

Packet::~Packet() {
}

void Packet::Init() {
	//instantiate the NAM
	networkAccessManager = new QNetworkAccessManager(this);

	//connect to the finished slot for the name
	bool connNAMres = QObject::connect(networkAccessManager,
			SIGNAL(finished(QNetworkReply*)),
			this,
			SLOT(RequestFinished(QNetworkReply*)));
	Q_ASSERT(connNAMres); //print to debug the result of the connect
	Q_UNUSED(connNAMres); //dispose unused bool
}

void Packet::PerformRequest() {
	//create the queue network request object
	QNetworkRequest request = QNetworkRequest();
	request.setUrl(QUrl(URL));

	networkAccessManager->get(request);
}

void Packet::RequestFinished(QNetworkReply* reply) {
	//check if the reply is successful

	if (reply->error() == QNetworkReply::NoError)
	{
		//on success, get the response text, and return it to the emitted OnSuccess signal
		QString replyText = QString(reply->readAll());
		emit OnSuccess(replyText);
	} else {
		//on error, return it to the OnError method with some response info
		emit OnError(reply->errorString());
	}
	reply->deleteLater();
}
